<?php
require('/www/web/majiang/public_html/server/crontab.php');
require('/www/web/majiang/public_html/server/library/db_mysql.inc.php');
$config_obj=Yaf_Registry::get("config");
$config_database =$config_obj->database->config->toArray();
$host =$config_database['host'];
$user =$config_database['user'];
$password =$config_database['pwd'];
$database =$config_database['name'];

$db = new DB_Sql($host, $user, $password, $database);

$redis = RedisDB::factory('user');
$list = $redis->hGetAll("userlist");

if(is_array($list) && $list){
	foreach($list as $uid=>$user){
		$userInfo =json_decode($user,true);
		if(!$userInfo['username']) continue;
		$dbUserInfo=$db->fetchRow("SELECT * FROM gm_users where fromuser='".$userInfo['username']."'");
		$scoreInfo = $redis->hGetAll("user:".$userInfo['uid']);
		$post =array(
							'uid'=>$userInfo['uid'],
							'fromuser'=>$userInfo['username'],
							'point'=>$scoreInfo['point'],
							'gold'=>$scoreInfo['gold'],
							'headimgurl'=>$userInfo['headimgurl'],
							'paiju'=>$scoreInfo['paiju'],
							'victory'=>$scoreInfo['victory'],
							'escape'=>$scoreInfo['escape'],
							'regdate'=>$userInfo['regdate'],
			);
		if(is_array($dbUserInfo)&&$dbUserInfo){
			//update
			$sqlArray = array();
			foreach($post as $key=>$value){
				 $sqlArray[] = "`{$key}`='{$value}'";
			}
			$sql = "update gm_users set ".implode(',',$sqlArray)." where fromuser='".$fromuser."'";
		}else{
			$keys = '`'.implode('`,`',array_keys($post)).'`';
			$values = "'".implode("','",$post)."'";
			$sql = "insert into gm_users ({$keys}) values ({$values})";
			$db->query($sql);
		}

		
		// $usersTable->add($post);
	}
}
// $count = 100;
// do{
// 	$now = time();
// 	$list = $redis->zRange(RoomModel::PLAYING_KEY, 0, -1, true);
// 	print_r($list);exit;
// 	foreach($list as $roomid => $expire){
// 		if($now < $expire){
// 			break;
// 		}
		
// 		$room = $redis->hGetAll(RoomModel::INFO_KEY . $roomid);
// 		$seatkey = "seat" . $room['current'];
// 		$seat = json_decode($room[$seatkey], true);
// 		$mUser = new UserModel($seat['uid']);
// 		$mRoom = new RoomModel($mUser, $roomid);
// 		$mRoom->giveup();
// 		unset($mUser, $mRoom);
// 	}
	
// 	sleep(2);
// }while(--$count > 0);